<script setup>
import {menuTypes} from './common.js'
import SettingMenuAPI from '@/api/setting/menu.js'
import {cloneDeep, trimStart} from "lodash-es";
import {arr2Tree, getMenuComponents, objMerge} from '@/utils/tools.js'
import {Plus, Delete} from '@element-plus/icons-vue'

const emits = defineEmits(["close"]);
const priId = ref(0)
const open = (id) => {
  if (id) {
    dialog.title = '编辑'
    priId.value = id
    SettingMenuAPI.getFormData(id).then(data => {
      objMerge(formData, data)
    })
  } else {
    dialog.title = '新增'
    priId.value = 0
  }
  dialog.visible = true;
  SettingMenuAPI.getList().then(res => {
    menuTreeData.value = arr2Tree(res.filter(v => v.type === 1))
  })
}
defineExpose({open});

const dialog = reactive({
  visible: false,
  title: "新增",
});

const formRef = ref();
let formData = reactive({
  type: 1,
  pid: 0,
  title: "",
  path: "",
  code: "",
  component: '',
  icon: "",
  redirect_path: null,
  sort: 0,
  hidden: 0,
  btns: [],
});

const rules = reactive({
  title: [{required: true, message: "不能为空", trigger: "blur"}],
  path: [{required: true, message: "不能为空", trigger: "blur"}],
  code: [{required: true, message: "不能为空", trigger: "blur"}],
  icon: [{required: true, message: "不能为空", trigger: "blur"}],
  btns: [{
    type: 'array',
    trigger: "blur",
    defaultField: {
      type: "object",
      trigger: "blur",
      fields: {
        title: [{required: true, message: "不能为空", trigger: "blur"}],
        code: [{required: true, message: "不能为空", trigger: "blur"}],
      },
    },
  }]

});


const __DialogClose = () => {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  menuTreeData.value = []
  prePath.value = ''
  formData.btns = []
  emits("close");
};


const __RadioChange = (e) => {
  formData.pid = 0
  prePath.value = ''
}

const menuTreeData = ref([])

const _submit = (formEl) => {
  if (!formEl) return
  console.log(formData)
  const data = cloneDeep(formData)
  formEl.validate((valid, fields) => {
    if (valid) {
      if (Array.isArray(data.pid)) {
        data.pid = data.pid[data.pid.length - 1];
      } else if (!data.pid) {
        data.pid = 0
      }
      if (data.type === 1) {
        data.component = data.pid === 0 ? 'Layout' : 'CLayout';
        if (data?.redirect_path && data.redirect_path.trim()) {
          data.redirect_path = '/' + trimStart(data.redirect_path, '/')
        }
      } else if (data.type === 2) {
        data.component = components.value.find((v) => v.name === data.code).path
      } else {
        data.icon = "Link"
      }
      if (priId.value > 0) {
        SettingMenuAPI.update(priId.value, data).then(res => {
          __DialogClose()
        })
      } else {
        SettingMenuAPI.add(data).then(res => {
          __DialogClose()
        })
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const components = getMenuComponents()
const cascaderRef = ref()
const prePath = ref('')
const __CascaderChange = (v) => {
  if (v) {
    const node = cascaderRef.value.getCheckedNodes()[0]
    prePath.value = node.data.pre_path + node.data.path + (node.data.path === '/' ? '' : '/')
  } else {
    prePath.value = ''
  }
  console.log('__CascaderChange', v, cascaderRef.value.getCheckedNodes())
}

const _addBtn = () => {
  formData.btns.push({
    code: '',
    title: '',
  })
}
const _rmBtn = (i) => {
  formData.btns.splice(i, 1)
}
</script>

<template>
  <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      destroy-on-close
      width="30vw"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="__DialogClose"
      draggable
  >
    <el-form ref="formRef" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="formData.type" @change="__RadioChange" :disabled="priId > 0">
          <el-radio v-for="item in menuTypes.filter(v => v.value !== 3)" :key="item.value" :value="item.value">
            {{ item.title }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上一级" prop="pid">
        <el-cascader
            ref="cascaderRef"
            v-model="formData.pid"
            :options="menuTreeData"
            :props="{ value: 'id', label: 'title', checkStrictly: true }"
            clearable
            @change="__CascaderChange"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="title">
        <el-input v-model="formData.title" maxlength="20" placeholder="名称"/>
      </el-form-item>
      <el-form-item v-if="formData.type === 1 || formData.type === 2" label="访问路径" prop="path">
        <el-input v-model="formData.path" placeholder="path">
          <template #prepend>{{ prePath }}</template>
        </el-input>
      </el-form-item>
      <el-form-item v-else label="访问路径" prop="path">
        <el-input v-model="formData.path" placeholder="path"></el-input>
      </el-form-item>
      <el-form-item v-if="formData.type === 1" label="重定向路径" prop="redirect_path">
        <el-input v-model="formData.redirect_path" placeholder="redirect_path"></el-input>
      </el-form-item>

      <el-form-item v-if="formData.type === 1" label="路由名称" prop="code">
        <el-input v-model="formData.code" maxlength="20" placeholder="code"/>
      </el-form-item>
      <el-form-item v-if="formData.type === 2" label="路由名称1" prop="code">
        <el-select v-model="formData.code">
          <el-option
              v-for="item in components"
              :key="item.name"
              :label="item.name + ' ' + item.path"
              :value="item.name"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
              {{ item.path }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.type !== 4" label="图标" prop="icon">
        <el-input v-model="formData.icon"
                  :formatter="(value) => value.replace(/\d+/g, '')"
                  :parser="(value) => value.replace(/\d+/g, '')"
                  placeholder="图标">
          <template #append>
            <el-icon v-if="formData.icon">
              <component :is="formData.icon"/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="路由显现" prop="hidden">
        <el-radio-group v-model="formData.hidden">
          <el-radio :value="0" border>显现</el-radio>
          <el-radio :value="1" border>隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" type="number" class="widthPx-150" placeholder="排序"/>
      </el-form-item>
      <el-form-item v-if="formData.type === 2" label="按键" prop="btns">
        <el-button type="primary" :icon="Plus" circle @click="_addBtn"/>
        <template v-for="(btn, index) in formData.btns">
          <div style="width: 100%; display: flex;padding: 4px;align-items: center;">
            <el-form-item label-width="40" label="名称" :prop="`btns.${index}.title`">
              <el-input v-model="btn.code"/>
            </el-form-item>
            <el-form-item label-width="<>50</>" label="标识" :prop="`btns.${index}.code`">
              <el-input v-model="btn.title"/>
            </el-form-item>
            <el-button type="danger" :icon="Delete" circle @click="_rmBtn(index)"/>
          </div>
        </template>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="__DialogClose">取 消</el-button>
        <el-button type="primary" @click="_submit(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>
